import { useEffect, useState } from 'react'
import { userSave } from '@api'
import { useNavigate } from 'react-router-dom'
import CryptoJS from 'crypto-js'
import { Form, Input, Button, Toast, Selector } from 'antd-mobile'
import './index.scss'

const LoginForm = () => {
    const navigate = useNavigate()

    const [level, setLevel] = useState([])

    const levelOptions = {
        0: [
            { label: '一级', value: 1 },
            { label: '二级', value: 2 },
            { label: '三级', value: 3 }
        ],
        1: [
            { label: '二级', value: 2 },
            { label: '三级', value: 3 }
        ],
        2: [
            { label: '三级', value: 3 }
        ]
    }

    useEffect(() => {
        const info = JSON.parse(localStorage.getItem('userInfo') || '{}')
        const levels = levelOptions[info.level] || [];
        setLevel(levels)
    }, [])

    const onFinish = (values) => {
        userSave({ ...values, password: CryptoJS.MD5(values.password).toString(), level: values.level[0] }).then(({ success, info }) => {
            if (success) {
                Toast.show({
                    content: '创建成功~'
                })
                navigate('/')
            } else {
                Toast.show({
                    content: info
                })
            }
        })
    }

    return (
        <div>
            <Form
                onFinish={onFinish}
                footer={
                    <Button block type="submit" color="primary" size="large">
                        提交
                    </Button>
                }
            >
                <Form.Item name="name" label="名称" rules={[{ required: true, message: '名称不能为空' }]}>
                    <Input placeholder="请输入名称" />
                </Form.Item>
                <Form.Item name="phone" label="账号" rules={[{ required: true, message: '账号不能为空' }]}>
                    <Input placeholder="请输入账号" />
                </Form.Item>
                <Form.Item name="password" label="密码" rules={[{ required: true, message: '密码不能为空' }]}>
                    <Input placeholder="请输入密码" />
                </Form.Item>
                <Form.Item name="level" label="账号等级" rules={[{ required: true, message: '账号等级不能为空' }]}>
                    <Selector columns={3} options={level} />
                </Form.Item>
            </Form>
        </div>
    )
}

export default LoginForm
